package com.hongxun.budget.ui.fragment.ys;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.tk.EditeLatLngActivity;
import com.hongxun.budget.ui.activity.ys.ChoiceYsPointActivity;
import com.hongxun.budget.ui.adapter.SpinnerAdapter;
import com.hongxun.budget.ui.fragment.BaseFragment;
import com.hongxun.budget.ui.view.BaseView;
import com.hongxun.budget.ui.view.ys.YSDLJView;
import com.hongxun.budget.ui.view.ys.YsCrossView;
import com.hongxun.budget.ui.view.ys.YsDahuodianView;
import com.hongxun.budget.ui.view.ys.YsGanTaView;
import com.hongxun.budget.ui.view.ys.YsXiaHuDianView;
import com.hongxun.budget.ui.view.ys.YsZsbyqView;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.LocationUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.budget.utils.TestingUtils;
import com.hongxun.entity.LineName;
import com.hongxun.entity.LoginInfo;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.ys.ECrossCostEntity;
import com.hongxun.greenentity.ys.EPBaseEntity;
import com.hongxun.greenentity.ys.EPointEntity;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2018/9/18.
 */

public class PointBasicCheckFragment extends BaseFragment {
    public static final int SET_LATLNG = 0x9999;//重新设置经纬度
    public static final int CHOICE_PARENT_POINT = 0x9998;//选择关联点位
    public static final int CHOICE_BEFORE_POINT = 0x9997;//选择上联点位


    @BindView(R.id.lat)
    TextView lat;
    @BindView(R.id.lgt)
    TextView lgt;
    @BindView(R.id.point_distance)
    EditText point_distance;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.point_type)
    TextView pointType;
    @BindView(R.id.parent_txt)
    TextView parentTxt;
    @BindView(R.id.parent_layout)
    LinearLayout parentLayout;
    @BindView(R.id.parent_code_txt)
    TextView parentCodeTxt;
    @BindView(R.id.parent_code_layout)
    LinearLayout parentCodeLayout;
    @BindView(R.id.content)
    LinearLayout content;
    @BindView(R.id.point_code_layout)
    LinearLayout pointCodeLayout;
    @BindView(R.id.voltage_layout)
    LinearLayout voltageLayout;
    @BindView(R.id.point_code)
    EditText pointCode;
    BaseView baseView = null;

    SpinnerAdapter<LineName> lineNameAdapter;
    SpinnerAdapter<BDataDictionaryEntity> voltageAdapter;

    Object o;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_ys_pointbasic;
    }

    @Override
    public void initView() {
        lat.setText((String) SPUtils.get(context, "drag_lat", ""));
        lgt.setText((String) SPUtils.get(context, "drag_lgt", ""));
        spinner.setAdapter(lineNameAdapter = new SpinnerAdapter<LineName>(context, DBUtils.getYsLineNames((String) SPUtils.get(context, "project_ys_guid", "")), spinner));
        spinner2.setAdapter(voltageAdapter = new SpinnerAdapter<BDataDictionaryEntity>(context, DBUtils.getBDataDictionaryEntities("voltage_type"), spinner2));
        pointType.setText((String) SPUtils.get(context, "point_name", ""));//point_name
        setVisible();
    }

    @Override
    public void initDault() {
        DBUtils.setYsDefaultLineName(context, spinner);
        DBUtils.setYsDefaultVoltage(context, spinner2);
        DBUtils.setYsPointCode(context, pointCode);
        if (o != null) updateInit(o);
    }

    public void setO(Object o) {
        this.o = o;
    }

    private void setVisible() {
        EPBaseEntity ap = DBUtils.getYsProject(context);
        if (ap.getPBType().equals("400")) {//设备
            parentCodeLayout.setVisibility(View.GONE);
            parentLayout.setVisibility(View.VISIBLE);
        } else {//架空
            parentCodeLayout.setVisibility(View.GONE);
            parentLayout.setVisibility(View.GONE);
            if (SPUtils.get(context, "process", "").equals("新增"))
                parentCodeLayout.setVisibility(View.VISIBLE);
            setView();
        }

    }

    private void setView() {
        content.removeAllViews();
        String pointName = (String) SPUtils.get(context, "point_name", "");
        switch (pointName) {
            case "搭火点":
                parentCodeLayout.setVisibility(View.GONE);
                voltageLayout.setVisibility(View.GONE);
                baseView = new YsDahuodianView(this);
                break;
            case "下户点":
            case "开关柜":
                baseView = new YsXiaHuDianView(this);
                break;
            case "交叉跨越":
                parentCodeLayout.setVisibility(View.GONE);
                pointCodeLayout.setVisibility(View.GONE);
                voltageLayout.setVisibility(View.GONE);
                baseView = new YsCrossView(this);
                break;
            case "杆塔":
                baseView = new YsGanTaView(this);
                break;
            case "柱上变压器":
                baseView = new YsZsbyqView(this);
                break;
            case "电缆井":
                baseView = new YSDLJView(this);
                break;
        }
        if (baseView != null) content.addView(baseView.getRootView());
    }


    @OnClick({R.id.latLng_set, R.id.parent_txt, R.id.parent_code_txt, R.id.l_location})
    public void onViewClicked(View view) {
        Intent intent = null;
        Double a = Double.parseDouble(lat.getText().toString());
        Double g = Double.parseDouble(lgt.getText().toString());
        switch (view.getId()) {
            case R.id.latLng_set://重新设置经纬度
                intent = new Intent(context, EditeLatLngActivity.class);
                intent.putExtra("lat", a);
                intent.putExtra("lgt", g);
                startActivityForResult(intent, SET_LATLNG);
                break;
            case R.id.parent_txt://选择关联点位
                intent = new Intent(context, ChoiceYsPointActivity.class);
                intent.putExtra("lat", a);
                intent.putExtra("lgt", g);
                startActivityForResult(intent, CHOICE_PARENT_POINT);
                break;
            case R.id.parent_code_txt://上联编号
                intent = new Intent(context, ChoiceYsPointActivity.class);
                intent.putExtra("lat", a);
                intent.putExtra("lgt", g);
                intent.putExtra("isUp", true);
                startActivityForResult(intent, CHOICE_BEFORE_POINT);
                break;
            case R.id.l_location:
                new LocationUtils(context, getActivity().getApplicationContext(), 3, 0, this);
                break;
        }
    }

    @Override
    public void success(int i, JSONObject obj) {
        SPUtils.put(context, "location_lat", obj.getDouble("latitude"));
        SPUtils.put(context, "location_lgt", obj.getDouble("longitude"));
        lat.setText(SPUtils.get(context, "location_lat", "").toString());
        lgt.setText(SPUtils.get(context, "location_lgt", "").toString());
        T.showLong(context, "已设置");
    }

    EPointEntity d;


    /**
     * 保存点位信息
     */
    public boolean save() {
        d = new EPointEntity();
        d.setGuid((String) SPUtils.get(context, "UUID", ""));
        d.setPGuid((String) SPUtils.get(context, "project_ys_guid", ""));
        d.setPPWorktype(SPUtils.get(context, "process", "").toString());
        if (lineNameAdapter.getSelectedItem() != null) {
            d.setPRGuid(lineNameAdapter.getSelectedItem().getGuid());
        }
        d.setPPName((String) SPUtils.get(context, "point_name", ""));
        d.setPPAutolatitude(Double.parseDouble((String) SPUtils.get(context, "location_lat", "")));
        d.setPPAutolongitude(Double.parseDouble((String) SPUtils.get(context, "location_lgt", "")));
        d.setPPInputlatitude(Double.parseDouble(lat.getText().toString()));
        d.setPPInputlongitude(Double.parseDouble(lgt.getText().toString()));
        d.setPPDatastate(o == null ? "新增" : "修改");
        d.setPPUserid(LoginInfo.getInfo(context).getUserId());
        d.setPPCollecttime(new Date());
        if (voltageAdapter.getSelectedItem() != null) {
            d.setPPVoltage(voltageAdapter.getSelectedItem().getDKey());
        }
        String pointCode = this.pointCode.getText().toString();
        if (!pointCode.contains("#")) {
            showMsg("点位编码必须包含 # ");
            return false;
        } else if (pointCode.split("#").length == 1) {
            showMsg(" # 后面必须是数字如:01,1 ...");
            return false;
        } else if (!TestingUtils.isNumeric(pointCode.split("#")[1])) {
            showMsg(" # 后面必须是数字如:01,1 ...");
            return false;
        }
        d.setPPCode(pointCode);
        String distance = point_distance.getText().toString().trim();
        if (!TestingUtils.isEmpty(context, distance, "人工转运")) {
            return false;
        }
        d.setPPDistanse(Double.parseDouble(distance));
        String beforeCode = parentCodeTxt.getText().toString();//上联点
        if (!TextUtils.isEmpty(beforeCode)) {
            d.setPPUpguid((String) parentCodeTxt.getTag());
        }
        String parentCode = parentTxt.getText().toString();//关联点
        if (!TextUtils.isEmpty(parentCode)) {//选择关联点之后坐标点和关联点的一致
            d.setPPParentguid((String) parentTxt.getTag());
            EPointEntity p = GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().load((String) parentTxt.getTag());
            d.setPPInputlatitude(p.getPPInputlatitude());
            d.setPPInputlongitude(p.getPPInputlongitude());
            d.setPPAutolatitude(p.getPPAutolatitude());
            d.setPPAutolongitude(p.getPPAutolongitude());
        }
        if (baseView != null)
            return baseView.save(d);
        return true;
    }

    public String getLineName() {
        return lineNameAdapter.getSelectedItem().getName();
    }

    public void insertDB() {
        if (baseView != null)
            baseView.insertDB();
        else
            GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().insertOrReplace(d);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            if (requestCode == SET_LATLNG) {
                if (baseView != null) {
                    baseView.setLatLng(Double.parseDouble(lat.getText().toString())
                            , Double.parseDouble(lgt.getText().toString()), data.getDoubleExtra("lat", 0), data.getDoubleExtra("lgt", 0));
                }
                lat.setText(data.getDoubleExtra("lat", 0) + "");
                lgt.setText(data.getDoubleExtra("lgt", 0) + "");
            } else if (requestCode == CHOICE_BEFORE_POINT) {
                EPointEntity d = (EPointEntity) data.getSerializableExtra("point");
                if (d == null) {
                    parentCodeTxt.setText("");
                    if (baseView != null) {
                        baseView.setSpan(null);
                    }
                } else {
                    if (d.getGuid().equals(SPUtils.get(context, "UUID", ""))) {
                        T.showShort(context, "请勿选择当前点位");
                    } else {
                        parentCodeTxt.setText(d.getPPCode());
                        parentCodeTxt.setTag(d.getGuid());
                        if (baseView != null) {
                            baseView.setSpan(d.getGuid());
                        }
                    }
                }
            } else if (requestCode == CHOICE_PARENT_POINT) {
                EPointEntity d = (EPointEntity) data.getSerializableExtra("point");
                if (d == null) {
                    parentTxt.setText("");
                } else {
                    if (d.getGuid().equals(SPUtils.get(context, "UUID", ""))) {
                        T.showShort(context, "请勿选择当前点位");
                    } else {
                        parentTxt.setText(d.getPPCode());
                        parentTxt.setTag(d.getGuid());
                    }
                }
            } else if (baseView != null) {
                baseView.result(requestCode, resultCode, data);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public Double getLat() {
        return Double.parseDouble(lat.getText().toString());
    }

    public Double getLgt() {
        return Double.parseDouble(lgt.getText().toString());
    }

    void updateInit(Object o) {//修改初始化
        if (o instanceof EPointEntity) {
            EPointEntity d = (EPointEntity) o;
            point_distance.setText(d.getPPDistanse() == null ? "0" : d.getPPDistanse() + "");
            lat.setText(d.getPPInputlatitude() + "");
            lgt.setText(d.getPPInputlongitude() + "");
            int i = 0;
            for (LineName l : DBUtils.getYsLineNames(d.getPGuid())) {//设置线路
                if (l.getGuid().equals(d.getPRGuid())) {
                    spinner.setSelection(i);
                    break;
                }
                i++;
            }
            i = 0;
            for (BDataDictionaryEntity b : DBUtils.getBDataDictionaryEntities("voltage_type")) {//设置电压等级
                if (b.getDKey().equals(d.getPPVoltage())) {
                    spinner2.setSelection(i);
                }
                i++;
            }
            pointType.setText(d.getPPName());
            pointCode.setText(d.getPPCode());
            if (!TextUtils.isEmpty(d.getPPParentguid())) {//说明有关联点
                EPointEntity pointEntity = GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().load(d.getPPParentguid());
                if (pointEntity != null) {
                    parentTxt.setText(pointEntity.getPPCode());
                    parentTxt.setTag(pointEntity.getGuid());
                }
            }
            if (!TextUtils.isEmpty(d.getPPUpguid())) {//说明有上联点
                EPointEntity pointEntity = GreenDaoManager.getInstance().getmDaoSession().getEPointEntityDao().load(d.getPPUpguid());
                if (pointEntity != null) {
                    parentCodeTxt.setText(pointEntity.getPPCode());
                    parentCodeTxt.setTag(pointEntity.getGuid());
                }
            }
        } else if (o instanceof ECrossCostEntity) {//交叉跨越初始化
            ECrossCostEntity d = (ECrossCostEntity) o;
            lat.setText(d.getCCInputlatitude() + "");
            lgt.setText(d.getCCInputlongitude() + "");
            int i = 0;
            for (LineName l : DBUtils.getLineNames(d.getPRGuid())) {//设置线路
                if (l.getGuid().equals(d.getPRGuid())) {
                    spinner.setSelection(i);
                    break;
                }
                i++;
            }
            pointType.setText("交叉跨越");
        }
    }
}
